package com.test.jms.topic;

import java.util.Hashtable;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ReportMessagePublisher {

	public static final String CONNECTION_FACTORY = "ConnectionFactory";
	public static final String TOPIC_REPORT_TOPIC = "topic/reportTopic";

	TopicConnection topicConnection;
	TopicSession topicSession;
	TopicPublisher topicPublisher;
	Topic topic;

	public ReportMessagePublisher(String factoryJNDI, String topicJNDI) throws NamingException, JMSException {

		Hashtable<String, String> props = new Hashtable<String, String>();
		props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		props.put(Context.PROVIDER_URL, "localhost:1099");
		props.put("java.naming.rmi.security.manager", "yes");
		props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming");

		Context context = new InitialContext(props);
		TopicConnectionFactory topicFactory = (TopicConnectionFactory) context.lookup(factoryJNDI);
		topicConnection = topicFactory.createTopicConnection();
		topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
		topic = (Topic) context.lookup(topicJNDI);
		topicPublisher = topicSession.createPublisher(topic);
	}

	public void publish(String msg) throws JMSException {
		TextMessage message = topicSession.createTextMessage();
		message.setText(msg);
		topicPublisher.publish(topic, message);
	}

	public void close() throws JMSException {
		topicSession.close();
		topicConnection.close();
	}

	public static void main(String[] args) {
		try {
			ReportMessagePublisher publisher = new ReportMessagePublisher(CONNECTION_FACTORY, TOPIC_REPORT_TOPIC);
			for (int i = 1; i < 11; i++) {
				String msg = "Report Message NO. " + i;
				System.out.println("Publishing message: " + msg);
				publisher.publish(msg);
			}

			publisher.close();
		} catch (Exception ex) {
			System.err.println("An exception occurred while testing ReportMessagePublisher: " + ex);
			ex.printStackTrace();
		}
	}

}
